/* Author: smayo@google.com

*/
var ZOO = window.ZOO || {};

window.URL = window.URL || window.webkitURL;
navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia ||
                          navigator.mozGetUserMedia || navigator.msGetUserMedia;

ZOO.Snapshot = function(){
  var pub = {
    video: null,
    canvas: null,
    ctx: null,
    photo: null,
    localMediaStream: null,
    filters: [
      'grayscale',
      'sepia',
      'blur',
      'brightness',
      'contrast',
      'hue-rotate', 'hue-rotate2', 'hue-rotate3',
      'saturate',
      'invert',
      ''
    ],
    idx: 0,

    init: function(){
      console.log('initsnapshot');

      //$(".alert").alert();

      if (this.hasGetUserMedia()) {
        console.log('hasGetUserMedia');
        this.video = document.querySelector('.video');
        this.canvas = document.querySelector('canvas');
        this.ctx = this.canvas.getContext('2d');
        this.photo = document.querySelector('.photo');

        //this.canvas.width = this.video.width;
        //this.canvas.height = this.video.height;

        console.log(this.video);
        navigator.getUserMedia({audio: false, video: true}, $.proxy(function(stream) {
          this.video.src = window.URL.createObjectURL(stream);
          this.localMediaStream = stream;
        }, this), this.onFailSoHard);

        $(this.video).on('click', $.proxy(function(e){
          this.changeFilter(e.currentTarget);
        }, this));
        $(this.photo).on('click', $.proxy(function(e){
          this.changeFilter(e.currentTarget);
        }, this));

      } else {
        alert('getUserMedia() is not supported in your browser');
      }

      return this;
    },
    hasGetUserMedia: function(){
      return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia || navigator.msGetUserMedia);
    },
    onFailSoHard: function(e){
      console.log(e);
    },
    takeSnapshot: function(){
      console.log(this);
      this.ctx.drawImage(this.video, 0, 0);
      this.photo.src = this.canvas.toDataURL('image/webp');
      this.photo.classList.toggle("hide");
    },
    retakeSnapshot: function(){
      this.photo.classList.toggle("hide");
      //this.photo.src = "";
    },
    changeFilter: function(el){
      this.video.className = '';
      //preserve the hide class if it exists on #photo
      this.photo.className = (this.photo.classList.contains('hide'))? 'hide' : '';
      var effect = this.filters[this.idx++ % this.filters.length];
      if (effect) {
        this.video.classList.add(effect);
        this.photo.classList.add(effect);
      }

    },



  }
  return pub;
};